package com.hbx.task.job;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hbx.constant.DateFormatContent;
import com.hbx.mapper.PkMapper;
import com.hbx.model.Pk;
import com.hbx.task.BaseJob;
import com.hbx.task.ScheduledJobEnum;
import com.hbx.utils.DateUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class PkExpireCheckJob extends BaseJob {

    @Autowired
    private PkMapper pkMapper;

    @Setter
    @Getter
    private List<Pk> pkList;

    @Override
    public ScheduledJobEnum getScheduledJobEnum() {
        return ScheduledJobEnum.PK_EXPIRE_TIME_JOB;
    }

    @Scheduled(cron = "0 0 0 * * ?")
    public void start(){
        execute();
    }


    @Override
    public Boolean beforeExecute() {
        List<Pk> pks = pkMapper.selectByPkEndTime(DateUtil.dateToString(new Date(), DateFormatContent.YYYY_MM_DD));
        if (CollectionUtils.isEmpty(pks)){
            return false;
        } else {
            List<Pk> list = pks.stream().filter(pk -> pk.getPkStatus() == 1).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(list)){
                log.info("【pkResultExpire定时任务】:pk表今日无到期pk,不执行");
                return false;
            }else {
                log.info("【pkResultExpire定时任务】:pk表今日到期pk,共{}条",list.size());
                this.pkList = list;
                return true;
            }
        }
    }

    @Override
    public void doExecute() {
        // 将pkStatus改为2
        if (!CollectionUtils.isEmpty(pkList)){
            List<Integer> ids = pkList.stream().map(Pk::getId).collect(Collectors.toList());
            UpdateWrapper<Pk> wrapper = new UpdateWrapper<>();
            wrapper.in("id",ids);
            Pk pk = new Pk();
            pk.setPkStatus(2);
            int update = pkMapper.update(pk, wrapper);
            if (update <= 0){
                log.error("【pkResultExpire定时任务】:result状态修改失败,ids:{}",ids);
                return;
            }
            log.info("【pkResultExpire定时任务】:result状态修改成功,影响行数:{}",update);

        }
    }

    @Override
    public void afterExecute() {
        log.info("【pkResultExpire定时任务】:执行完毕");
    }
}
